
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from tortoise.contrib.fastapi import register_tortoise
from admin.fastapi_admin.factory import app as admin_app
from setting import TORTOISE_ORM,SECRET_KEY,CORS_ORIGINS
from fastapi.staticfiles import StaticFiles
from aioredis import create_redis_pool
from setting import REDIS_URL,STATIC_PATH

def register_redis(app: FastAPI) -> None:
    """
    把redis挂载到app对象上面
    :param app:
    :return:
    """
    @app.on_event('startup')
    async def startup_event():
        """
        获取链接
        :return:
        """
        app.state.redis = await create_redis_pool(REDIS_URL)

    @app.on_event('shutdown')
    async def shutdown_event():
        """
        关闭
        :return:
        """
        app.state.redis.close()
        await app.state.redis.wait_closed()

def create_app():
    fast_app = FastAPI(debug=False)
    register_tortoise(fast_app,
                      config=TORTOISE_ORM,
                      generate_schemas=False,
                      add_exception_handlers=False,
                      )
    fast_app.mount("/" + STATIC_PATH, StaticFiles(directory=STATIC_PATH), name=STATIC_PATH)
    fast_app.add_middleware(
        CORSMiddleware,
        allow_origins=CORS_ORIGINS,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    register_redis(fast_app) #注册redis到fast_app
    return fast_app
app = create_app()

##路由注册
from blog import api
from admin import api as admin_api

app.include_router(api.router, prefix='/api')
app.mount('/api',admin_app)
admin_app.include_router(admin_api.router)



from admin.site_config import site
@app.on_event("startup")
async def start_up():
    await admin_app.init(  # nosec
        admin_secret=SECRET_KEY,
        permission=True,
        admin_log=True,
        login_view='admin.login_view.login',
        site = site,
    )



if __name__ == "__main__":
    import uvicorn
    uvicorn.run("main:app", port=8000,proxy_headers=True,forwarded_allow_ips='*', debug=True, reload=True, lifespan="on")
#     uvicorn main._main:app --port 8000 --reload --proxy-headers --forwarded-allow-ips='*'